#!/usr/bin/env python
# encoding: utf-8

"""
@author: liuxiandong
@contact: liuxiandong@37.com
@file: devicesoption.py
@time: 2021/3/22 10:00
@desc:
"""
import os
import subprocess
from performance.Command import *

def run_cmd(cmd):
    '''
    后面在统一使用该接口
    :param cmd:
    :return:
    '''
    ret = os.popen(cmd)
    return ret

def get_devices():
    _str = os.popen("adb devices").readlines()
    _str.pop(0)
    _str.pop(-1)
    device = []
    if _str:
        for i in _str:
            if 'device' in i:
                _i = i.split('\t')[0]
                device.append(_i)
            else:
                print('设备尚未连接！')
    return device

def get_sdk_version(device):
    if device is None:
        print('设备没有连接！')
        return FALIE
    api_verison = int(os.popen('adb -s %s shell getprop ro.build.version.sdk' % device).read())
    return api_verison

def get_packages(device):
    package_list = []
    if device is None:
        print('设备没有连接！')
        return FALIE
    api_verison = get_sdk_version(device)
    print(api_verison)
    if api_verison < 29:
        packages_list = os.popen('adb -s %s shell "dumpsys window | grep mCurrentFocus"' % device).read()
    else:
        packages_list = os.popen('adb -s %s shell "dumpsys window  | grep mCurrentFocus"' % device).read()
    if packages_list is None:
        return FALIE
    package = packages_list.strip().rstrip('\n').split('u0')[1].rstrip('}').strip().split('/')[0]
    package_list.append(package)
    # pack_list = list(set(package_list))
    print( package_list)
    return package_list

def get_pid(device, packagename):
    pid_info = os.popen('adb -s %s shell "ps | grep %s"' % (device, packagename)).read().strip()
    if pid_info is None:
        return 'pid获取为空'
    pid_list = pid_info.split(" ")
    for p in pid_list:
        if p == '':
            pid_list.remove(p)
    pid = int(pid_list[1])
    print(pid)
    return pid

def get_memory(device, packagename):
    if device is None or packagename is None:
        print('设备为空！')
        return FALIE
    else:
        meminfo = {}
        meminfo_list = os.popen('adb -s %s shell "dumpsys meminfo -s %s"' % (device, packagename)).readlines()
        # print(meminfo_list)
        for total in meminfo_list:
            if 'TOTAL' in total:
                t_list = total.strip().split(" ")
                mem_list = [i for i in t_list if i != '']
                mem = int(mem_list[1])
                if mem is None:
                    print('数据为空')
                else:
                    meminfo['mem'] = round(mem / 1024, 2)
        return meminfo

def get_cpu(device, packagename):
    if device is None or packagename is None:
        print('设备为空！')
        return FALIE
    else:
        # cpuinfo = {}
        CPUTime = 0
        pid = get_pid(device, packagename)
        print(pid)
        cpuinfo_list = os.popen('adb -s %s shell "cat /proc/%s/stat"' % (device, pid)).read().split(" ")[13:17]
        processCPUTime = int(cpuinfo_list[0]) + int(cpuinfo_list[1]) + int(cpuinfo_list[2]) + int(cpuinfo_list[3])
        CPU = os.popen('adb -s %s shell "cat /proc/stat"' % device).readlines()[0].strip().split(" ")[2:]
        for i in range(len(CPU)):
            CPUTime += int(CPU[i])
        return processCPUTime, CPUTime


def get_dfx(device, packagename):
    """
    目前帧率fps使用dumpsys SurfaceFlinger --lateency <Layer>是获取不到cocos引擎游戏的帧率数据
    :param device:
    :param packagename:
    :return:
    """
    if device is None or packagename is None:
        print('设备为空！')
        return FALIE
    else:
        os.popen('adb -s %s shell dumpsys SurfaceFlinger --latency-clear'%device)
        sdk_version = get_sdk_version(device)
        print(sdk_version)
        if sdk_version <= 23:
            surview = os.popen('adb -s %s shell dumpsys "window windows | grep mCurrentFocus"'%device).read().strip().split('u0')[1].strip().rstrip('}')
            gfxinfo = os.popen('adb -s %s shell dumpsys "SurfaceFlinger --latency %s"' % (device, surview)).read()
            print(gfxinfo)
        elif 23 < sdk_version <= 26:
            surview = os.popen('adb -s %s shell dumpsys "window windows | grep mCurrentFocus"'%device).read().strip().split('u0')[1].strip().rstrip('}')
            gfxinfo = os.popen('adb -s %s shell dumpsys "SurfaceFlinger --latency %s"' % (device, surview)).\
                read()
            print(gfxinfo)
        elif sdk_version > 26 :
            surview = os.popen('adb -s %s shell dumpsys "window | grep mCurrentFocus"'%device).read().strip().split('u0')[1].strip().rstrip('}') + "#0"
            print(surview)
            gfxinfo = os.popen('adb -s %s shell dumpsys "SurfaceFlinger --latency %s"' % (device, surview)).read()
            print(gfxinfo)


if __name__ == '__main__':
    # get_dfx("06157df6a8717027","com.sqhy.sgbyslg.stable.test")
    # get_dfx("c5306b75","com.sqhy.sgbyslg.stable.test")
    # get_dfx("1f4af0c5","com.tencent.tmgp.sgame")
    # get_dfx("FMGNW19916004315","com.sqhy.sgbyslg.stable.test")
    # get_pid(device='c5306b75', packagename='com.sqhy.sgbyslg.stable')
    # get_pid(device='FMGNW19916004315', packagename='com.sqhy.sgbyslg.stable.test')
    get_packages('c5306b75')
    get_memory('c5306b75','com.sqhy.sgbyslg.stable')
    # get_cpu(device='c5306b75', packagename='com.sqhy.sgbyslg.stable.test')
